package com.example.service.impl;

import com.example.domain.LoginUser;
import com.example.domain.enums.AppHttpCodeEnum;
import com.example.domain.po.MenuPO;
import com.example.domain.po.RolePO;
import com.example.domain.po.UserPO;
import com.example.exception.SystemException;
import com.example.mapper.MenuMapper;
import com.example.mapper.RoleMapper;
import com.example.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author hlc
 * @version 1.0
 * @date 2022/10/15 15:09
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    private final MenuMapper menuMapper;

    public UserDetailsServiceImpl(UserMapper userMapper, RoleMapper roleMapper, MenuMapper menuMapper) {
        this.userMapper = userMapper;
        this.roleMapper = roleMapper;
        this.menuMapper = menuMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserPO user = userMapper.selectByUserName(username);
        if (Objects.isNull(user)) {
            throw new SystemException(AppHttpCodeEnum.LOGIN_ERROR);
        }
        RolePO role = roleMapper.selectRoleByUserId(user.getId());
        List<MenuPO> menus = menuMapper.selectMenuByRoleId(role.getId());
        List<String> permissions = menus.stream().map(MenuPO::getPerms).collect(Collectors.toList());
        return new LoginUser(user, permissions);
    }
}
